<?php

namespace App\Exports;

use App\Models\AgentRevenue;
use Illuminate\Database\Eloquent\Builder;
use Illuminate\Support\Carbon;
use Maatwebsite\Excel\Concerns\FromQuery;
use Maatwebsite\Excel\Concerns\WithCustomValueBinder;
use PhpOffice\PhpSpreadsheet\Cell\Cell;
use PhpOffice\PhpSpreadsheet\Cell\DataType;

class FinanceDetailsExport extends BaseExport implements WithCustomValueBinder, FromQuery
{
    public function headings(): array
    {
        return [
            '序号',
            '类型',
            '金额',
            '代理手机号',
            '创建时间',
            '操作后余额',
            '关联订单号',
//            '代付订单号',
        ];
    }

    public function map($row): array
    {
        return [
            $row['id'],
            AgentRevenue::TYPE_MAP[$row['type']] ?? '',
            number_format(((($row['revenues_type'] === AgentRevenue::REVENUES_TYPE_EXPENDITURE) ? -1 : 1) * $row['amount']) / 100, 2),
            $row['agent']['phone'] ?? '',
            $row['created_at'],
            number_format(($row['balance'] + $row['unextractable_balance']) / 100, 2),
            $row['source']['numbering'] ?? '',
//            '', // TODO
        ];
    }

    /**
     * @return \Illuminate\Database\Query\Builder
     */
    public function query()
    {
        return AgentRevenue::query()
            ->with(['source', 'agent'])
            ->when($this->request['phone'] ?? '', function (Builder $builder, $phone) {
                $builder
                    ->join('agents', 'agents.id', '=', 'agent_revenues.agent_id')
                    ->where('agents.phone', 'like', "$phone%");
            })
            ->when($this->request['type'] ?? 0, function (Builder $query, $type) {
                $query->where('agent_revenues.type', $type);
            })
            ->when($this->request['created_at_begin'] ?? '', function (Builder $query, $createdAtBegin) {
                $query->where('agent_revenues.created_at', '>=', Carbon::parse($createdAtBegin)->startOfDay());
            })
            ->when($this->request['created_at_end'] ?? '', function (Builder $query, $createdAtEnd) {
                $query->where('agent_revenues.created_at', '<=', Carbon::parse($createdAtEnd)->endOfDay());
            })
            ->select(['agent_revenues.*']);
    }

    public function bindValue(Cell $cell, $value)
    {
        // 金额和操作后的余额不要字符串
        if (!in_array($cell->getColumn(), ['C', 'F'])) {
            $cell->setValueExplicit($value, DataType::TYPE_STRING);

            return true;
        }

        // else return default behavior
        return parent::bindValue($cell, $value);
    }
}
